package com.tql.hualala;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;

import com.tql.hualala.request.*;
import com.tql.hualala.response.BaseResponse;
import com.tql.hualala.response.DocOpenFoodResponse;
import com.tql.hualala.response.QueryBillDetailByReportDateResponse;
import com.tql.hualala.util.ResponseFormatter;

import com.tql.hualala.util.CommonUtil;
import com.tql.hualala.util.WebUtil;
import com.tql.hualala.bean.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

public class HuaLaLaApi {




    @Log(title = "获取集团下所有的店", businessType = BusinessType.UPDATE)
    public static List<ShopBean> getDocAllShops(Long groupID) {
        if(null==groupID)groupID= CommonUtil.GROUP_ID;
        List<ShopBean> list = null;
        DocGetAllShopsRequest request = new DocGetAllShopsRequest();
        request.setGroupID(groupID);
        BaseBean bean = new BaseBean();
        bean.setGroupID(groupID);
        request.setRequestBody(bean);

        try {
            System.out.println("****************************************");
            System.out.println(request.getRequestBody().toString());
            System.out.println(request.getShopID());
            System.out.println(request.getPath());
            System.out.println(request.getGroupID());
            String response = WebUtil.post(request);
            System.out.println("getDocAllShops----response-------->" + response);
            BaseResponse baseResponse = ResponseFormatter.format(response, BaseResponse.class);
            if ("000".equals(baseResponse.getCode())) {
                JSONObject data = (JSONObject) baseResponse.getData();
                JSONObject result = data.getJSONObject("result");
                String code = result.getString("code");
                if ("000".equals(code)) {
                    JSONArray shopInfoList = data.getJSONArray("shopInfoList");
                    list = new ArrayList<>();
                    for (Object each : shopInfoList) {
                        JSONObject jo = (JSONObject) each;
                        ShopBean shop = getShopBean(jo);
                        list.add(shop);
                    }

                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            //  logger.error("getDocAllShops 异常. groupID: {}", groupID, e);

        }

        return list;
    }



    @Log(title = "获取集团下某个店的所有菜品", businessType = BusinessType.UPDATE)
    public static List<FoodBean> getMenu(Long groupID, Long shopID) {
        DocOpenFoodResponse response = null;

        DocOpenFoodRequest request = new DocOpenFoodRequest();
        request.setGroupID(groupID);
        request.setShopID(shopID);
        DocBaseInfoBean requestBody = new DocBaseInfoBean();
        requestBody.setGroupID(groupID);
        requestBody.setShopID(shopID);
        request.setRequestBody(requestBody);

        try {
            String resp = WebUtil.post(request);
            System.out.println(resp);
            response = ResponseFormatter.format(resp, DocOpenFoodResponse.class);
            if ("000".equals(response.getCode())) {
                JSONObject jo = response.getData();
                JSONObject joResult = (JSONObject) jo.get("result");
                //String EBookVersionNo=jo.getString("EBookVersionNo");
                String code = joResult.getString("code");
                if ("000".equals(code)) {
                   // JSONObject pageHeader = (JSONObject) jo.get("pageHeader");
                   // String totalSize= (String) pageHeader.get("totalSize");


                        JSONArray joFoodList = jo.getJSONArray("foodList");
                        if(null!=joFoodList&&joFoodList.size()>0)
                        {
                            List<FoodBean> list = trans(joFoodList);
                            return list;
                        }



                } else {
                    return null;
                }

            } else {
                return null;
            }


        } catch (Exception e) {
            e.printStackTrace();
            //log.error("getMenu 异常. groupID: {} shopID: {}", groupID, shopID, e);
        }


        return null;
    }


    /***
     * 获取历史账单数据
     * http://open.web.hualala.com/resource/204?parent_str=22,38,342,16186,48
     * @param groupID 集团ID
      @param shopID 店铺ID
      @param reportDate 报表日期 yyyyMMDD 20240103
     * @return
     * 接口简介
     * 获取历史账单数据，是用来分页获取指定集团指定店铺指定日期的账单数据，获取到的数据和商户中心-报表中心-收银明细表数据一致。
     *
     * 注意：此接口因数据量较大，需低峰调用，调用时间建议T+1，02:00-05:00。
     *
     * 对接口实时性要求高的话，请对接【变更账单推送】，如【变更账单推送】因异常未接收到全部数据，此接口也可作为补偿方案进行调用，调用时间建议T+1，02:00-05:00。
     *
     * 通过获取历史账单数据获取的是截止当前最新的数据，可能会遇到获取报表数据后，pos修改账单再上传的情况，所以建议对接【变更账单推送】；如果必须要调用此接口，在pos修改账单后，需要重新调用才能获取到最新的数据
     *
     * 接口调用地址：/report/getShopBillDetail
     */
    @Log(title = "获取集团下某个店每天的账单", businessType = BusinessType.UPDATE)
public static List<ShopBillDetailBean> getShopBillDetail(long groupID, long shopID, long reportDate)
{
    //0.先访问接口，获取pageTotal
    List<ShopBillDetailBean> list=null;
//10012_204 执行成功，无返回内容
    QueryBillDetailByReportDateResponse response= queryBillDetailByReportDate(groupID,shopID,reportDate,1,1);
    String code=response.getCode();
    int count=0;
    if("000".equals(code)) {
        JSONObject jo = response.getData();
        JSONObject responseHeader = jo.getJSONObject("responseHeader");
        String code1 = responseHeader.getString("code");
        if ("000".equals(code1)) {
            /**
             * --PageResponseInfo（账单数据分页信息）：
             * 名称	类型	说明
             * totalSize	String	账单数据总条数
             * pageTotal	String	总页数
             * pageNo	String	当前页码
             * pageSize	String	每页大小
             */
            JSONObject pageResponseInfo = jo.getJSONObject("pageResponseInfo");
            //  String totalSize=pageResponseInfo.getString("totalSize");
            if(null!=pageResponseInfo) {
                String totalSize = pageResponseInfo.getString("totalSize");
                count = Integer.parseInt(totalSize);
                response = null;
            }
        }
    }

    //1.遍历pageTotal,封装起来list
    if(count>0){
         list=new ArrayList<>();
         int pageSize=50;
         int pageNum=(count/pageSize)+1;
        for(int i=1;i<=pageNum;i++)
        {
            List<ShopBillDetailBean> arr=getShopBillDetailBeanList(groupID,shopID,reportDate,i,pageSize);
            list.addAll(arr);
        }
    }


    return list;
}


    private static List<ShopBillDetailBean> getShopBillDetailBeanList(long groupID, long shopID, long reportDate,int pageNo,int pageSize) {


        List<ShopBillDetailBean> list=null;
        QueryBillDetailByReportDateResponse response= queryBillDetailByReportDate(groupID,shopID,reportDate,pageNo,pageSize);
        String code=response.getCode();
        if("000".equals(code))
        {
            JSONObject jo=response.getData();
            JSONObject responseHeader=jo.getJSONObject("responseHeader");
            String code1=responseHeader.getString("code");
            if("000".equals(code1))
            {
                JSONArray billDetails=jo.getJSONArray("billDetail");
                if(null!=billDetails&&billDetails.size()>0)
                {
                    list=new ArrayList<>();
                    for(Object ele:billDetails){
                        //主表billDetailMain
                        JSONObject billDetail=(JSONObject)ele;
                        //UUID主表和子表关联
                        String uuid=UUID.randomUUID().toString();
                        BillDetailBean billDetailMain=getBillDetailBean(billDetail);
                        //主表对应的foodDetail,一对多
                        JSONArray foodDetail=billDetail.getJSONArray("foodDetail");
                        List<FoodDetailBean> foodDetailBeanList=new ArrayList<>();
                        if(null!=foodDetail&&foodDetail.size()>0)
                        {
                            for(Object each:foodDetail)
                            {
                                JSONObject food=(JSONObject)each;
                                FoodDetailBean bean=getFoodDetailBean(food);
                                bean.setUuid(uuid);
                                foodDetailBeanList.add(bean);
                            }
                        }

                        billDetailMain.setUuid(uuid);
                        ShopBillDetailBean vo=new ShopBillDetailBean();
                        vo.setFoodDetailBeanList(foodDetailBeanList);
                        vo.setBillDetailBean(billDetailMain);
                        list.add(vo);
                    }

                }

            }
        }
return list;
    }

    private static BillDetailBean getBillDetailBean(JSONObject ele) {
        BillDetailBean bean=new BillDetailBean();
       // groupID	Long	集团ID
       Long groupID= ele.getLong("groupID");
       bean.setGroupID(groupID);
       // shopID	Long	店铺ID
        Long shopID= ele.getLong("shopID");
        bean.setShopID(shopID);
       // shopName	String	店铺名称
        String shopName= ele.getString("shopName");
        bean.setShopName(shopName);
        //reportDate	Long	报表统计日期，门店增加数据清机结转时间设定，该时间为次日小时数（1~12），默认为1，即次日凌晨1点，格式：yyyyMMdd，默认值0
        Long reportDate= ele.getLong("reportDate");
        bean.setReportDate(reportDate);
       // saasOrderKey	String	账单号，格式：YYYYMMDD-ID-日流水号
        String saasOrderKey= ele.getString("saasOrderKey");
        bean.setSaasOrderKey(saasOrderKey);
       // orderStatus	Integer	账单状态 40：已结账 30：已作废
        Integer orderStatus= ele.getInteger("orderStatus");
        bean.setOrderStatus(orderStatus);
       // saasOrderNo	String	日流水号
        String saasOrderNo= ele.getString("saasOrderNo");
        bean.setSaasOrderNo(saasOrderNo);
       // foodAmount	String	账单菜品金额（流水金额）=paidAmount+promotionAmount
        String foodAmount= ele.getString("foodAmount");
        bean.setFoodAmount(foodAmount);
       // promotionAmount	String	账单优惠金额
        String promotionAmount= ele.getString("promotionAmount");
        bean.setPromotionAmount(promotionAmount);
      //  paidAmount	String	账单实收金额=foodAmount-promotionAmount
        String paidAmount= ele.getString("paidAmount");
        bean.setPaidAmount(paidAmount);
        //actionTime	Long	记录修改时间，格式：yyyyMMddHHmmss，默认值0
        Long actionTime= ele.getLong("actionTime");
        bean.setActionTime(actionTime);
        //areaName	String	所属区域名称
        String areaName= ele.getString("areaName");
        bean.setAreaName(areaName);
//        cardKey	String	会员卡Key
        String cardKey= ele.getString("cardKey");
        bean.setCardKey(cardKey);
//        cardNo	String	会员卡号
        String cardNo= ele.getString("cardNo");
        bean.setCardNo(cardNo);
//        cardTransAfterRemark	String	会员卡交易后资金信息
        String cardTransAfterRemark= ele.getString("cardTransAfterRemark");
        bean.setCardTransAfterRemark(cardTransAfterRemark);
//        cardTransID	String	会员卡交易ID
        String cardTransID= ele.getString("cardTransID");
        bean.setCardTransID(cardTransID);
//        channelKey	String	渠道Key
        String channelKey= ele.getString("channelKey");
        bean.setChannelKey(channelKey);
//        channelName	String	订单来源渠道名称
        String channelName= ele.getString("channelName");
        bean.setChannelName(channelName);
//        channelOrderKey	String	渠道订单Key
        String channelOrderKey= ele.getString("channelOrderKey");
        bean.setChannelOrderKey(channelOrderKey);
//        channelOrderKeyTP	String	第三方订单号
        String channelOrderKeyTP= ele.getString("channelOrderKeyTP");
        bean.setChannelOrderKeyTP(channelOrderKeyTP);
//        channelOrderNo	String	渠道订单号
        String channelOrderNo= ele.getString("channelOrderNo");
        bean.setChannelOrderNo(channelOrderNo);
       // chargeBackFlag	Integer	冲销标识，空值: POS版本不支持此字段. 0: 正常单(默认), 1: 退单, 2: 冲销单, 3: 部分冲销单
        Integer chargeBackFlag= ele.getInteger("chargeBackFlag");
        bean.setChargeBackFlag(chargeBackFlag);
    return bean;
    }

    private static FoodDetailBean getFoodDetailBean(JSONObject food) {
        FoodDetailBean bean =new FoodDetailBean();
    Long groupId=food.getLong("groupID");
    bean.setGroupID(groupId);
        Long shopID=food.getLong("shopID");
        bean.setShopID(shopID);
        String shopName=food.getString("shopName");
        bean.setShopName(shopName);
        Long reportDate=food.getLong("reportDate");
        bean.setReportDate(reportDate);
        String saasOrderKey=food.getString("saasOrderKey");
        bean.setSaasOrderKey(saasOrderKey);
        Integer orderStatus=food.getInteger("orderStatus");
        bean.setOrderStatus(orderStatus);
        Integer orderSubType=food.getInteger("orderSubType");
        bean.setOrderSubType(orderSubType);
        String foodName=food.getString("foodName");
        bean.setFoodName(foodName);
        String foodCode=food.getString("foodCode");
        bean.setFoodCode(foodCode);
        String foodKey=food.getString("foodKey");
        bean.setFoodKey(foodKey);
        String unit=food.getString("unit");
        bean.setUnit(unit);
        String unitKey=food.getString("unitKey");
        bean.setUnitKey(unitKey);
        String oodNumber=food.getString("oodNumber");
        bean.setOodNumber(oodNumber);
        String foodCancelNumber=food.getString("foodCancelNumber");
        bean.setFoodCancelNumber(foodCancelNumber);
        String foodSendNumber=food.getString("foodSendNumber");
        bean.setFoodSendNumber(foodSendNumber);
        String foodPriceAmount=food.getString("foodPriceAmount");
        bean.setFoodPriceAmount(foodPriceAmount);
        String foodRealAmount=food.getString("foodRealAmount");
        bean.setFoodRealAmount(foodRealAmount);
        String foodRealPrice=food.getString("foodRealPrice");
        bean.setFoodRealPrice(foodRealPrice);
        String foodProPrice=food.getString("foodProPrice");
        bean.setFoodProPrice(foodProPrice);
        String foodVipPrice=food.getString("foodVipPrice");
        bean.setFoodVipPrice(foodVipPrice);
        String actionBatchNo=food.getString("actionBatchNo");
        bean.setActionBatchNo(actionBatchNo);
        Integer isSetFood=food.getInteger("isSetFood");
        bean.setIsSetFood(isSetFood);
        Integer isSFDetail=food.getInteger("isSFDetail");
        bean.setIsSFDetail(isSFDetail);
        Integer isTempFood=food.getInteger("isTempFood");
        bean.setIsTempFood(isTempFood);
        String parentFoodFromItemKey=food.getString("parentFoodFromItemKey");
        bean.setParentFoodFromItemKey(parentFoodFromItemKey);
        String setFoodCategoryName=food.getString("setFoodCategoryName");
        bean.setSetFoodCategoryName(setFoodCategoryName);
        String setFoodName=food.getString("setFoodName");
        bean.setSetFoodName(setFoodName);
        String setFoodRemark=food.getString("setFoodRemark");
        bean.setSetFoodRemark(setFoodRemark);
        String departmentKeyOne=food.getString("departmentKeyOne");
        bean.setDepartmentKeyOne(departmentKeyOne);
        return bean;
    }

    public static QueryBillDetailByReportDateResponse queryBillDetailByReportDate(long groupID, long shopID, long reportDate, int pageNo, int pageSize) {
        QueryBillDetailByReportDateResponse response = null;
        try {
            QueryBillDetailByReportDateRequest request = new QueryBillDetailByReportDateRequest();
            request.setGroupID(groupID);
            request.setShopID(shopID);
            QueryBillDetailByReportDateBean bean = new QueryBillDetailByReportDateBean();
            bean.setGroupID(groupID);
            bean.setShopID(shopID);
            bean.setReportDate(reportDate);
            bean.setPageNo(pageNo);
            bean.setPageSize(pageSize);
            request.setRequestBody(bean);

            String resp = WebUtil.post(request);
            response = ResponseFormatter.format(resp, QueryBillDetailByReportDateResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
           // log.error("queryBillDetailByReportDate 异常. groupID: {} shopID: {} date: {} page: {}-{}", groupID, shopID, reportDate, pageNo, pageSize, e);
        }

        return response;
    }





    private static ShopBean getShopBean(JSONObject jo) {
        ShopBean shopBean = new ShopBean();

        String shopCity = jo.getString("shopCity");
        shopBean.setShopCity(shopCity);
        String brandName = jo.getString("brandName");
        shopBean.setBrandName(brandName);
        String actionTime = jo.getString("actionTime");
        shopBean.setActionTime(actionTime);
        String imagePath = jo.getString("imagePath");
        shopBean.setImagePath(imagePath);
        String groupID1 = jo.getString("groupID");
        shopBean.setGroupID(groupID1);
        String businessModel = jo.getString("businessModel");
        shopBean.setBusinessModel(businessModel);
        String shopName = jo.getString("shopName");
        shopBean.setShopName(shopName);
        String shopOpenTime = jo.getString("shopOpenTime");
        shopBean.setShopOpenTime(shopOpenTime);
        String shopAddress = jo.getString("shopAddress");
        shopBean.setShopAddress(shopAddress);
//        String mapLongitudeValueBaiDu = jo.getString("mapLongitudeValueBaiDu");
//        shopBean.setMapLongitudeValueBaiDu(mapLongitudeValueBaiDu);
//        String mapLatitudeValueBaiDu = jo.getString("mapLatitudeValueBaiDu");
//        shopBean.setMapLatitudeValueBaiDu(mapLatitudeValueBaiDu);
        String operationMode = jo.getString("operationMode");
        shopBean.setOperationMode(operationMode);
        String acspType = jo.getString("acspType");
        shopBean.setAcspType(acspType);
        String pinyin = jo.getString("pinyin");
        shopBean.setPinyin(pinyin);
        String createTime = jo.getString("createTime");
        shopBean.setCreateTime(createTime);
        String orgCode = jo.getString("orgCode");
        shopBean.setOrgCode(orgCode);
        String brandID = jo.getString("brandID");
        shopBean.setBrandID(brandID);
        String shopCityName = jo.getString("shopCityName");
        shopBean.setShopCityName(shopCityName);
        String action = jo.getString("action");
        shopBean.setAction(action);
        String shopPhone = jo.getString("shopPhone");
        shopBean.setShopPhone(shopPhone);
        String shopID = jo.getString("shopID");
        shopBean.setShopID(shopID);
        String status = jo.getString("status");
        shopBean.setStatus(status);
        return shopBean;
    }



    private static List<FoodBean> trans(JSONArray joFoodList) {

        if (joFoodList.size() < 1) return null;
        List<FoodBean> list = new ArrayList<>();
        for (Object each : joFoodList) {
            FoodBean foodBean = new FoodBean();
            JSONObject JO = (JSONObject) each;
            String isActive = JO.getString("isActive");
            foodBean.setIsActive(isActive);
            String foodName = JO.getString("foodName");
            foodBean.setFoodName(foodName);
            String foodCategoryKey = JO.getString("foodCategoryKey");
            foodBean.setFoodCategoryKey(foodCategoryKey);
            String foodCategoryCode = JO.getString("foodCategoryCode");
            foodBean.setFoodCategoryCode(foodCategoryCode);
            String foodCategoryName = JO.getString("foodCategoryName");
            foodBean.setFoodCategoryName(foodCategoryName);
            String foodType = JO.getString("foodType");
            foodBean.setFoodType(foodType);
            String foodID = JO.getString("foodID");
            foodBean.setFoodID(foodID);
            String groupID = JO.getString("groupID");
            foodBean.setGroupID(groupID);
            String shopID = JO.getString("shopID");
            foodBean.setShopID(shopID);
            String departmentID = JO.getString("departmentID");
            foodBean.setDepartmentID(departmentID);
            String parentFoodID = JO.getString("parentFoodID");
            foodBean.setParentFoodID(parentFoodID);
            String isOpen = JO.getString("isOpen");
            foodBean.setIsOpen(isOpen);
            String isNews = JO.getString("isNews");
            foodBean.setIsNews(isNews);
            String foodMnemonicCode = JO.getString("foodMnemonicCode");
            foodBean.setFoodMnemonicCode(foodMnemonicCode);
            String foodCode = JO.getString("foodCode");
            foodBean.setFoodCode(foodCode);
            JSONArray units = JO.getJSONArray("units");
            ArrayList<UnitsBean> unitArray = new ArrayList();
            for (Object element : units) {
                JSONObject ele = (JSONObject) element;
                UnitsBean unit = getUnitBean(ele,foodID);
                unitArray.add(unit);
            }
            foodBean.setUnits(unitArray);
            list.add(foodBean);
        }
        return list;


    }

    private static UnitsBean getUnitBean(JSONObject JO,String foodID) {
        UnitsBean bean = new UnitsBean();

        String unitPackFee = JO.getString("unitPackFee");
        bean.setUnitPackFee(unitPackFee);
        String actionTime = JO.getString("actionTime");
        bean.setActionTime(actionTime);
        String originalPrice = JO.getString("originalPrice");
        bean.setOriginalPrice(originalPrice);
        String foodScore = JO.getString("foodScore");
        bean.setFoodScore(foodScore);
        String unitKey = JO.getString("unitKey");
        bean.setUnitKey(unitKey);
        String price = JO.getString("price");
        bean.setPrice(price);
        String specialPrice = JO.getString("specialPrice");
        bean.setSpecialPrice(specialPrice);
        String specialPrice2 = JO.getString("specialPrice2");
        bean.setSpecialPrice2(specialPrice2);
        String specialPrice3 = JO.getString("specialPrice3");
        bean.setSpecialPrice3(specialPrice3);
        String specialPrice4 = JO.getString("specialPrice4");
        bean.setSpecialPrice4(specialPrice4);
        String specialPrice5 = JO.getString("specialPrice5");
        bean.setSpecialPrice5(specialPrice5);
        String specialPrice6 = JO.getString("specialPrice6");
        bean.setSpecialPrice6(specialPrice6);
        String onlineTsPrice = JO.getString("onlineTsPrice");
        bean.setOnlineTsPrice(onlineTsPrice);
        String vipPrice = JO.getString("vipPrice");
        bean.setVipPrice(vipPrice);
        String unitPackCount = JO.getString("unitPackCount");
        bean.setUnitPackCount(unitPackCount);
        String ztVipPrice = JO.getString("ztVipPrice");
        bean.setZtVipPrice(ztVipPrice);
        String onlineWmPrice = JO.getString("onlineWmPrice");
        bean.setOnlineWmPrice(onlineWmPrice);
        String action = JO.getString("action");
        bean.setAction(action);
        String originalVipPrice = JO.getString("originalVipPrice");
        bean.setOriginalVipPrice(originalVipPrice);
        String foodEstimateCost = JO.getString("foodEstimateCost");
        bean.setFoodEstimateCost(foodEstimateCost);
        String unitTransferCommission = JO.getString("unitTransferCommission");
        bean.setUnitTransferCommission(unitTransferCommission);
        String tsVipPrice = JO.getString("tsVipPrice");
        bean.setTsVipPrice(tsVipPrice);
        String unitMakeCommission = JO.getString("unitMakeCommission");
        bean.setUnitMakeCommission(unitMakeCommission);
        String onlineZtPrice = JO.getString("onlineZtPrice");
        bean.setOnlineZtPrice(onlineZtPrice);
        String unitSalesCommission = JO.getString("unitSalesCommission");
        bean.setUnitSalesCommission(unitSalesCommission);
        String unitAssignCommission = JO.getString("unitAssignCommission");
        bean.setUnitAssignCommission(unitAssignCommission);
        String unitPieceCommission = JO.getString("unitPieceCommission");
        bean.setUnitPieceCommission(unitPieceCommission);
        String unit = JO.getString("unit");
        bean.setUnit(unit);
        String wmVipPrice = JO.getString("wmVipPrice");
        bean.setWmVipPrice(wmVipPrice);
        String wdPrice = JO.getString("wdPrice");
        bean.setWdPrice(wdPrice);
        String unitTakeawayTag = JO.getString("unitTakeawayTag");
        bean.setUnitTakeawayTag(unitTakeawayTag);
        String unitSortIndex = JO.getString("unitSortIndex");
        bean.setUnitSortIndex(unitSortIndex);
        bean.setFoodId(foodID);
        bean.setOrigin(CommonUtil.Food_Origin_Type_HUALALA);
        return bean;
    }


    //appKey
    final static String APP_KEY = "2060";
    //appSecret
    final static String APP_SECRET = "0RecrzOrNSykYqVP";

    private static String getRequestBody(String groupID) {
        HashMap requestBody1 = new HashMap();
        requestBody1.put("groupID", groupID);
        //  String s=new Gson().toJson(requestBody1);
        String param = JSONObject.toJSONString(requestBody1);
        return param;
    }

    //BaseRequest
    public static void main22(String[] args) throws Exception {
        BaseRequest request=new BaseRequest();
        request.setGroupID(247692l);
        request.setShopID(76927618l);
        request.setPath("/v2/doc/queryFoodCategory");
        String response = WebUtil.post(request);
        System.out.println(response);
    }
    public static void main(String[] args) {
//        List<ShopBean> list=  HuaLaLaApi.getDocAllShops(247692l) ;
//        System.out.println(list);
        List<FoodBean> list= HuaLaLaApi.getMenu(247692l, 76591388l);

        if(null!=list) {
            List<FoodBean> result = list.stream()
                    .filter(food -> food.getFoodName().contains("青南瓜"))
                    .collect(Collectors.toList());
            System.out.println("-----------------------------------------------------");
            result.forEach(item -> System.out.println(item.toString()));
        }
//List<ShopBillDetailBean>  list=  HuaLaLaApi.getShopBillDetail(247692l, 76591358l, 20221012);
        //  QueryBillDetailByReportDateResponse list2= queryBillDetailByReportDate(247692l,76591358l,20240101,0,1000);
        // System.out.println(list);


//        V2ShopFoodCategory v2ShopFoodCategory=new V2ShopFoodCategory();
//        v2ShopFoodCategory.setGroupID(CommonUtil.GROUP_ID);
//        v2ShopFoodCategory.setShopID(76591358l);
    }
    public static void main12(String[] args) throws Exception {

        // 创建请求头参数
        Map<String, Object> requestHeaders = new HashMap<>();
        requestHeaders.put("traceID", UUID.randomUUID().toString()); // 请求唯一标识，通过程序生成uuid即可
        requestHeaders.put("groupID", 247692l);// 集团ID
        requestHeaders.put("shopID", "76591358l"); // 店铺ID（调用接口时，若集团授权开发者该接口权限为店铺权限，shopID必传）

        // 创建请求体参数
        Map<String, Object> requestBodyParams = new HashMap<>();
        long timestamp = System.currentTimeMillis();
        System.out.println("timestamp---------->" + timestamp);
        //timestamp
        requestBodyParams.put("timestamp", timestamp); // 13位的毫秒时间戳
        //appkey
        requestBodyParams.put("appKey", "2060"); // 开发者Key

        //version
        requestBodyParams.put("version", "3"); // 版本号固定为3
        //requestBody
        String param = getRequestBody("247692");
        requestBodyParams.put("requestBody", param); // 业务参数，格式为jsonString
        StringBuilder sb = new StringBuilder();
        sb.append(APP_KEY).append(APP_SECRET).append(timestamp).append(param);
        System.out.println("sb--------->" + sb);

        //加密签名
        String signature = DigestUtils.md5Hex(sb.toString());
        //signature
        requestBodyParams.put("signature", signature); // 签名，具体生成方式请参照签名生成规则
        System.out.println("signature----------->" + signature);

        // 创建请求体字符串
        String requestBody = new Gson().toJson(requestBodyParams);
        System.out.println("requestBody-------------->" + requestBody);
        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象并设置URL和请求体类型
            HttpPost httpPost = new HttpPost("https://www-openapi.hualala.com/doc/getAllShop");
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setHeader("charset", StandardCharsets.UTF_8.name()); // 设置字符集为UTF-8
            httpPost.setEntity(new StringEntity(requestBody, StandardCharsets.UTF_8)); // 设置请求体内容为之前创建的requestBody字符串
            String version = "3";
            httpPost.setEntity(new StringEntity(version));
            // httpPost.setEntity(new StringEntity(version, StandardCharsets.UTF_8)); // 设置请求体内容为之前创建的requestBody字符串
            // 设置请求头参数到请求中
            for (Map.Entry<String, Object> entry : requestHeaders.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue().toString());
            }

            // 执行请求并获取响应内容
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8); // 将响应内容转换为字符串并打印出来
                    System.out.println(responseBody); // 打印响应内容，根据实际需求进行处理
                }
            } catch (Exception e) {
                e.printStackTrace(); // 如果出现异常，打印异常信息进行调试处理
            } finally {
                httpPost.releaseConnection(); // 释放连接资源，避免资源泄露问题发生。注意：此方法必须在finally块中调用。
            }
        } catch (Exception e) {
            e.printStackTrace(); // 如果出现异常，打印异常信息进行调试处理
        } finally {
            System.out.println();
        }
    }


    public static void main1(String[] args) {

        //traceId
        System.out.println(UUID.randomUUID().toString().replace("-", ""));

        //appKey
        final String APP_KEY = "2060";
        //appSecret
        final String APP_SECRET = "0RecrzOrNSykYqVP";
        //timestamp
        final Long TIMESTAMP = System.currentTimeMillis();
        System.out.println(TIMESTAMP);
        //请求jsonString
        Map<String, Object> map = new LinkedHashMap<>(16);
        map.put("groupID", "247692");
        //   map.put("shopID","76591356");
        //  map.put("traceID",0);
//        map.put("pageNo",1);
//        map.put("pageSize",10);

        String param = JSONObject.toJSONString(map);
        StringBuilder sb = new StringBuilder();
        sb.append(APP_KEY).append(APP_SECRET).append(TIMESTAMP).append(param);
        System.out.println(sb);

        //加密签名
        String signature = DigestUtils.md5Hex(sb.toString());
        System.out.println(signature);
    }


    private String getSignature() {
        final String APP_KEY = CommonUtil.HUALALA_APP_KEY;
        //appSecret
        final String APP_SECRET =CommonUtil.HUALALA_APP_SECRET ;
        //timestamp
        final Long TIMESTAMP = System.currentTimeMillis();
        System.out.println(TIMESTAMP);
        //请求jsonString
        Map<String, Object> map = new LinkedHashMap<>(16);
        map.put("groupID", CommonUtil.HUALALA_APP_GROUPID_STRING );
        //   map.put("shopID","76591356");
        //  map.put("traceID",0);
//        map.put("pageNo",1);
//        map.put("pageSize",10);

        String param = JSONObject.toJSONString(map);
        StringBuilder sb = new StringBuilder();
        sb.append(APP_KEY).append(APP_SECRET).append(TIMESTAMP).append(param);
        System.out.println(sb);

        //加密签名
        String signature = DigestUtils.md5Hex(sb.toString());
        System.out.println(signature);
        return signature;
    }
}
